﻿namespace ShellNavigator.Client.Forms
{
  #region

  using System.Windows;
  using System.Windows.Controls;

  #endregion

  public static class TreeViewHelper
  {
    #region Constants and Fields

    public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached(
      "Attach", typeof(bool), typeof(TreeViewHelper), new PropertyMetadata(false, Attach));

    public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.RegisterAttached(
      "SelectedItem", typeof(object), typeof(TreeViewHelper), new FrameworkPropertyMetadata(string.Empty));

    #endregion

    #region Public Methods

    public static bool GetAttach(DependencyObject dp)
    {
      return (bool)dp.GetValue(AttachProperty);
    }

    public static object GetSelectedItem(DependencyObject dp)
    {
      return dp.GetValue(SelectedItemProperty);
    }

    public static void SetAttach(DependencyObject dp, bool value)
    {
      dp.SetValue(AttachProperty, value);
    }

    public static void SetSelectedItem(DependencyObject dp, object value)
    {
      dp.SetValue(SelectedItemProperty, value);
    }

    #endregion

    #region Methods

    private static void Attach(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
      TreeView treeView = sender as TreeView;

      if (treeView == null)
      {
        return;
      }

      if ((bool)e.OldValue)
      {
        treeView.SelectedItemChanged -= SelectedItemChanged;
      }

      if ((bool)e.NewValue)
      {
        treeView.SelectedItemChanged += SelectedItemChanged;
      }
    }

    private static void SelectedItemChanged(object sender, RoutedEventArgs e)
    {
      TreeView treeView = sender as TreeView;

      if (treeView != null)
      {
        SetSelectedItem(treeView, treeView.SelectedItem);
      }
    }

    #endregion
  }
}